package com.weavernorth.attendance.util;

//import com.qiyuesuo.pdf.text.M;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Encoder;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 推送到sap考勤异常数据的工具类
 *
 * @author XvFei
 * @version V1.0 created by XvFei at 2020-02-18
 */
public class ToSapUtil {

    /**
     * 日志打印对象
     */
    private static Logger log = LoggerFactory.getLogger(ToSapUtil.class);

    /**
     * 组装考勤异常记录推送到sap的xml格式的信息
     *
     * @param listParam 要传送的数据集合
     * @param strType   那种类型的推送数据
     * @return
     */
    public static StringBuffer getRequestXml(List<Map<String, Object>> listParam, String strType) {
        //报文请求体
        StringBuffer requestXml = new StringBuffer();
        //拼接请求体
        requestXml.append("<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' ")
                .append("xmlns:urn='urn:sap-com:document:sap:soap:functions:mc-style'>")
                .append("<soapenv:Header/>")
                .append("<soapenv:Body>")
                .append("<urn:Zhri071>");


        for (int ind = 0; ind < listParam.size(); ind++) {
            if ("2010".equals(strType)) {
//                if (ind != 0) {
//                    String strCurrType = listParam.get(ind).get("kqtype").toString();
//                    String strLastType = listParam.get(ind - 1).get("kqtype").toString();
//                    log.info("strCurrType:" + strCurrType);
//                    log.info("strLastType:" + strLastType);
//                    if (!strCurrType.equals(strLastType)) {
//                        requestXml.append("<IZtype>").append(listParam.get(ind).get("kqtype")).append("</IZtype>");
//                        requestXml.append("<TP2010>");
//                    }
//                }
                if (ind == 0) {
                    requestXml.append("<IZtype>").append(listParam.get(ind).get("kqtype")).append("</IZtype>");
                    requestXml.append("<TP2010>");
                }

                requestXml.append("<item>")
                        .append("<Pernr>").append(listParam.get(ind).get("workcode")).append("</Pernr>")
                        .append("<Begda>").append(listParam.get(ind).get("kqdate")).append("</Begda>")
                        .append("<Lgart>").append(listParam.get(ind).get("salarytype")).append("</Lgart>")
                        .append("<Anzhl>").append(listParam.get(ind).get("num")).append("</Anzhl>")
                        .append("</item>");

//                if (ind != (listParam.size()-1)) {
//                    String strCurrType = listParam.get(ind).get("kqtype").toString();
//                    String strNextType = listParam.get(ind + 1).get("kqtype").toString();
//                    if (!(strCurrType).equals(strNextType)) {
//                        requestXml.append("</TP2010>");
//                    }
//                }
                if (ind == (listParam.size() - 1)) {
                    requestXml.append("</TP2010>");
                }
            } else {
//                if (ind != 0) {
//                    String strCurrType = listParam.get(ind).get("kqtype").toString();
//                    String strLastType = listParam.get(ind - 1).get("kqtype").toString();
//                    if (!strCurrType.equals(strLastType)) {
//                        requestXml.append("<IZtype>").append(listParam.get(ind).get("kqtype")).append("</IZtype>");
//                        requestXml.append("<TP0015>");
//                    }
//
//                }
                if (ind == 0) {
                    requestXml.append("<IZtype>").append(listParam.get(ind).get("kqtype")).append("</IZtype>");
                    requestXml.append("<TP0015>");
                }


                requestXml.append("<item>")
                        .append("<Pernr>").append(listParam.get(ind).get("workcode")).append("</Pernr>")
                        .append("<Begda>").append(listParam.get(ind).get("kqdate")).append("</Begda>")
                        .append("<Lgart>").append(listParam.get(ind).get("salarytype")).append("</Lgart>")
                        .append("<Betrg>").append(listParam.get(ind).get("num")).append("</Betrg>")
                        .append("</item>");
//                if (ind == (listParam.size() - 1)) {
//                    requestXml.append("</TP0015>");
//                }

//                if (ind != (listParam.size()-1)) {
//                    String strCurrType = listParam.get(ind).get("kqtype").toString();
//                    String strNextType = listParam.get(ind + 1).get("kqtype").toString();
//                    if (!(strCurrType).equals(strNextType)) {
//                        requestXml.append("</TP0015>");
//                    }
//                }
                if (ind == (listParam.size() - 1)) {
                    requestXml.append("</TP0015>");
                }
            }
        }

        //如果是0015类型，则只加一次2010xml
        if ("0015".equals(strType)) {
            requestXml.append("<TP2010>")
                    .append("<!--Zero or more repetitions:-->")
                    .append("<item>")
                    .append("<Pernr></Pernr>")
                    .append("<Begda></Begda>")
                    .append("<Lgart></Lgart>")
                    .append("<Anzhl></Anzhl>")
                    .append("</item>")
                    .append("</TP2010>");
        } else {
            requestXml.append("<TP0015>")
                    .append("<!--Zero or more repetitions:-->")
                    .append("<item>")
                    .append("<Pernr></Pernr>")
                    .append("<Begda></Begda>")
                    .append("<Lgart></Lgart>")
                    .append("<Betrg></Betrg>")
                    .append("</item>")
                    .append("</TP0015>");
        }

        requestXml.append("<TReturn>")
                .append("<!--Zero or more repetitions:-->")
                .append("<item>")
                .append("<Type></Type>")
                .append("<Id></Id>")
                .append("<Number></Number>")
                .append("<Message></Message>")
                .append("<LogNo></LogNo>")
                .append("<LogMsgNo></LogMsgNo>")
                .append("<MessageV1></MessageV1>")
                .append("<MessageV2></MessageV2>")
                .append("<MessageV3></MessageV3>")
                .append("<MessageV4></MessageV4>")
                .append("</item>")
                .append("</TReturn>")
                .append("</urn:Zhri071>")
                .append("</soapenv:Body>")
                .append("</soapenv:Envelope>");
        log.info("拼接 后的xml:" + requestXml);

        return requestXml;
    }

    /**
     * 发送post请求
     *
     * @param strUrl        路径
     * @param strRequestXml 参数(String类型)
     * @param strEncoding   编码格式
     * @return
     * @throws IOException
     */
    public static String sendPost(String strUrl, String strRequestXml, String strEncoding) throws IOException {
        //基础类
        BaseBean bb = new BaseBean();

        String strBody = "";
        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();

        //创建post方式请求对象
        try {
            HttpPost httpPost = new HttpPost(strUrl);
            //装填参数
            StringEntity stringEntity = new StringEntity(strRequestXml, "utf-8");
            //设置参数到请求对象中
            httpPost.setEntity(stringEntity);
            log.info("请求地址=" + strUrl);
            //获取用户名
            String strUsername = Util.null2String(bb.getPropValue("kqtosap", "userName"));
            log.info("用户名:" + strUsername);
            //获取密码
            String strPassword = Util.null2String(bb.getPropValue("kqtosap", "password"));
            log.info("密码:" + strPassword);
            //sap的接口需验证
            String strValue = "Basic " + (new BASE64Encoder().encode((strUsername + ":" + strPassword).getBytes()));
            httpPost.setHeader("Authorization", strValue);
            httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");

            //执行请求操作，并拿到结果（同步阻塞）
            CloseableHttpResponse response = client.execute(httpPost);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                strBody = EntityUtils.toString(entity, strEncoding);
                log.info("返回结果=" + strBody);
            }
            EntityUtils.consume(entity);
            //释放链接
            response.close();
        } catch (Exception e) {
            log.info("异常捕获=" + e);
        }
        return strBody;
    }

    /**
     * 获取上一个月的第一天日期
     *
     * @return
     */
    public static String getPreMonthFirstDate() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -1);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        return format.format(calendar.getTime());
    }

    /**
     * 获取上一个月的最后一天日期
     *
     * @return
     */
    public static String getPreMonthLastDate() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        int month = calendar.get(Calendar.MONTH);
        calendar.set(Calendar.MONTH, month - 1);
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        return format.format(calendar.getTime());
    }


    /**
     * 获取当前月的第几天
     *
     * @param intCurDay 当前月哪一天
     * @return
     */
    public static String getCurYearAndMonth(int intCurDay) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, 0);
        calendar.set(Calendar.DAY_OF_MONTH, intCurDay);
        return format.format(calendar.getTime());
    }

    /**
     * 判断当前用户是否满足条件
     *
     * @param intUserId 人员id
     * @return
     */
    public static boolean isCanToSapByUserId(int intUserId) {

        RecordSet rs = new RecordSet();
        rs.executeQuery("select 1 from cus_fielddata cfd,uf_ppkqgzhsfw ufp where ufp.gzhsfw = cfd.field23 " +
                " and cfd.scopeid=1 and cfd.id = ?", intUserId);

        if (rs.next()) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 得到当前的类型
     *
     * @param intUserId 人员id
     * @return
     */
    public static String getUserIdType(int intUserId, String strTypeField) {

        RecordSet rs = new RecordSet();
        //返回值
        String strResult = "";
        rs.executeQuery("select ufp." + strTypeField + " from cus_fielddata cfd,uf_ppkqgzhsfw ufp where ufp.gzhsfw = cfd.field23 " +
                " and cfd.scopeid=1 and cfd.id = ?", intUserId);

        if (rs.next()) {
            strResult = Util.null2String(rs.getString(strTypeField));
        }
        return strResult;
    }


    /**
     * 获取所有请假(事假和病假)的人员
     */

    public List<Map<String,String>> getLeaveData(String strKsrq, String strJsrq) {
        RecordSet rs = new RecordSet();

        List listReturn = new ArrayList<Map<String,String>>();
        String strSql = "SELECT resourceid,newleavetype,durationrule, min(belongdate) qjksrq, max(belongdate) qjjsrq," +
                "SUM (duration) AS val FROM  kq_flow_split_leave WHERE belongdate >=?" +
                "AND belongdate <= ? and  newleavetype in(6,7) GROUP BY resourceid, newleavetype, durationrule";
        log.info("得到请假人员的数据:" + strSql);
        rs.executeQuery(strSql, strKsrq, strJsrq);
        while (rs.next()) {
            Map<String,String> mapReturn = new HashMap<String,String>();
            //人员id
            String strResourceid = Util.null2String(rs.getString("resourceid"));
            //请假类型
            String strNewleavetype = Util.null2String(rs.getString("newleavetype"));
            mapReturn.put("newleavetype", strNewleavetype);
            //请假天数
            String strVal = Util.null2String(rs.getString("val"));
            //请假开始日期
            String strQjKsrq = Util.null2String(rs.getString("qjksrq"));
            //请假结束日期
            String strQjjsrq = Util.null2String(rs.getString("qjjsrq"));
            mapReturn.put("resourceid", strResourceid);
            mapReturn.put("leavedays", strVal);
            mapReturn.put("leavedate", strQjKsrq);
            mapReturn.put("enddate", strQjjsrq);
            listReturn.add(mapReturn);
        }

        return listReturn;
    }




    /**
     * 获取所有请假(事假和病假)的人员
     */

    public BigDecimal getLeavebackData(String strKsrq, String strJsrq,int intNewLeavetype,int intUserid) {
        RecordSet rs = new RecordSet();
        BigDecimal bigDecimal=new BigDecimal("0");
        String strSql = "SELECT resourceid,newleavetype,durationrule, min(belongdate) qjksrq, max(belongdate)," +
                "SUM (duration) AS val FROM  kq_flow_split_leaveback WHERE belongdate >=?" +
                "AND belongdate <= ? and  newleavetype in(6,7) and newleavetype=? and resourceid=? GROUP BY resourceid, newleavetype, durationrule";
        log.info("得到销假人员的数据:" + strSql+",strKsrq:"+strKsrq+",strJsrq:"+strJsrq+",intNewLeavetype:"+intNewLeavetype+",intUserid:"+intUserid);
        rs.executeQuery(strSql, strKsrq, strJsrq,intNewLeavetype,intUserid);
        if (rs.next()) {
            bigDecimal=new BigDecimal(Util.null2o(rs.getString("val")));
        }

        return bigDecimal;
    }

}
